package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext orderContext = (CreateOrderContext) context;
        List<CartProductDto> dtoList = orderContext.getCartProductDtoList();
        List<Long> productIds = orderContext.getBuyProductIds();

        if (CollectionUtils.isEmpty(productIds)){
            productIds = new ArrayList<>();
            for (CartProductDto cartProductDto : dtoList) {
                productIds.add(cartProductDto.getProductId());
            }
        }
        //锁定库存
        List<Stock> stockList = stockMapper.findStocksForUpdate(productIds);

        //异常判断
        if (CollectionUtils.isEmpty(stockList)){
            throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),
                    OrderRetCode.DB_EXCEPTION.getMessage()+"库存未初始化");
        }
        if (productIds.size()!=stockList.size()){
            throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),
                    OrderRetCode.DB_EXCEPTION.getMessage()+"部分商品库存未初始化");
        }
        //更新库存
        for (CartProductDto cartProductDto : dtoList) {
            Long itemId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();

            Stock stock = new Stock();
            stock.setItemId(itemId);
            //productNum不能超出限购数量
            Integer restrictCount = stockMapper.selectOne(stock).getRestrictCount();
            if (productNum>restrictCount){
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),
                        OrderRetCode.DB_EXCEPTION.getMessage()+"超出限购数量");
            }
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);
            stockMapper.updateStock(stock);
        }
        return true;
    }
}